<template>
  <div class="app-container product-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option label="新鲜蔬菜" :value="1" />
          <el-option label="时令水果" :value="2" />
          <el-option label="优质肉禽" :value="3" />
          <el-option label="新鲜水产" :value="4" />
          <el-option label="米面粮油" :value="5" />
          <el-option label="调味干货" :value="6" />
          <el-option label="乳制品" :value="7" />
          <el-option label="健康饮料" :value="8" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="已上架" :value="1" />
          <el-option label="已下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-select v-model="queryParams.isRecommend" placeholder="请选择" clearable>
          <el-option label="已推荐" :value="1" />
          <el-option label="未推荐" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" :disabled="multiple" @click="handleBatchStatus(1)">批量上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" :disabled="multiple" @click="handleBatchStatus(0)">批量下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-star-on" size="mini" :disabled="multiple" @click="handleBatchRecommend(1)">批量推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-star-off" size="mini" :disabled="multiple" @click="handleBatchRecommend(0)">取消推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="produceList" 
      @selection-change="handleSelectionChange"
      class="product-table"
      :header-cell-style="{background:'#f5f7fa',color:'#606266',fontWeight:'600'}"
      stripe
      :height="tableHeight"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="70">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="农产品图片" align="center" min-width="110">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.images" 
            :src="scope.row.images.split(',')[0]" 
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" 
          />
          <span v-else style="color: #ccc;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="农产品名称" align="center" prop="name" min-width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="product-name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户名称" align="center" prop="merchantName" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="merchant-name">
            <i class="el-icon-office-building"></i> {{ scope.row.merchantName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="农产品类型" align="center" prop="categoryName" min-width="120">
        <template slot-scope="scope">
          <el-tag size="mini" effect="plain" type="">{{ scope.row.categoryName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" min-width="100">
        <template slot-scope="scope">
          <span class="price-text">{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160">
        <template slot-scope="scope">
          <div class="time-wrapper">
            <i class="el-icon-time"></i>
            <span>{{ scope.row.createTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isRecommend === 1" type="danger" size="small" effect="dark">
            <i class="el-icon-star-on"></i> 推荐
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">不推荐</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="small" effect="dark">
            <i class="el-icon-success"></i> 已上架
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">
            <i class="el-icon-circle-close"></i> 未上架
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color: #F56C6C;">删除</el-button>
          <el-button v-if="scope.row.status === 1" size="mini" type="text" @click="handleStatusChange(scope.row, 0)">下架</el-button>
          <el-button v-else size="mini" type="text" @click="handleStatusChange(scope.row, 1)">上架</el-button>
          <el-button size="mini" type="text" @click="handleRecommend(scope.row)">推荐</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品图片" prop="images">
              <image-upload v-model="form.images" :limit="9" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%;">
                <el-option label="新鲜蔬菜" :value="1" />
                <el-option label="时令水果" :value="2" />
                <el-option label="优质肉禽" :value="3" />
                <el-option label="新鲜水产" :value="4" />
                <el-option label="米面粮油" :value="5" />
                <el-option label="调味干货" :value="6" />
                <el-option label="乳制品" :value="7" />
                <el-option label="健康饮料" :value="8" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格(元)" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐状态" prop="isRecommend">
              <el-radio-group v-model="form.isRecommend">
                <el-radio :label="1">推荐</el-radio>
                <el-radio :label="0">不推荐</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品详情" prop="detail">
              <el-input v-model="form.detail" type="textarea" :rows="4" placeholder="请输入产品详情" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQueryProduce, getProduce, addProduce, updateProduce, delProduce, updateProduceStatus, updateProduceRecommend, pushFarmProduce, unpushFarmProduce, recommendFarmProduce, unrecommendFarmProduce, exportProduce } from "@/api/yjnb/produce";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "Produce",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      produceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        name: null,
        categoryId: null,
        status: null,
        isRecommend: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "产品分类不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      // 滚动到表格顶部，增加交互效果
      this.scrollToTop();
      
      const params = { ...this.queryParams };
      // 添加时间范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginTime = this.dateRange[0];
        params.endTime = this.dateRange[1];
      }
      
      pageQueryProduce(params).then(response => {
        // 添加短暂延迟，让用户看到加载动画
        setTimeout(() => {
          this.produceList = response.rows;
          this.total = response.total;
          this.loading = false;
        }, 300);
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 滚动到顶部 */
    scrollToTop() {
      // 查找表格容器
      const container = document.querySelector('.app-container');
      if (container) {
        container.scrollIntoView({ 
          behavior: 'smooth',
          block: 'start'
        });
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        name: null,
        images: null,
        price: null,
        status: 1,
        isRecommend: 0,
        detail: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      console.log('🆕 打开新增窗口');
      console.log('🖼️ 重置后 form.images 的值：', this.form.images);
      this.open = true;
      this.title = "添加产品";
    },
    /** 弹窗关闭时重置表单 */
    handleClose() {
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      
      console.log('✏️ 打开编辑窗口，产品ID：', id);
      console.log('🖼️ 重置后 form.images 的值：', this.form.images);
      
      // 调用详情接口获取数据
      getProduce(id).then(response => {
        this.form = response.data;
        console.log('📥 从后端获取的数据：', this.form);
        console.log('🖼️ 后端返回的 images：', this.form.images);
        this.open = true;
        this.title = "修改产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 打印表单数据，验证图片是否为逗号分隔
          console.log('📝 提交表单数据：', this.form);
          console.log('🖼️ 图片数据（逗号分隔）：', this.form.images);
          
          if (this.form.id != null) {
            // 编辑
            updateProduce(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addProduce(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作（单个或批量） */
    handleDelete(row) {
      // 判断是否是有效的产品对象（避免事件对象被误判）
      const isValidRow = row && row.id && row.name;
      
      // 单个删除：传入单个ID；批量删除：传入ID数组
      const ids = isValidRow ? [row.id] : this.ids;
      
      console.log('删除操作 - row:', row);
      console.log('删除操作 - isValidRow:', isValidRow);
      console.log('删除操作 - this.ids:', this.ids);
      console.log('删除操作 - ids:', ids);
      
      // 检查是否选中了要删除的数据
      if (!ids || ids.length === 0) {
        this.$message.warning('请选择要删除的产品');
        return;
      }
      
      const message = isValidRow 
        ? `是否确认删除产品"${row.name}"？` 
        : `是否确认删除选中的${ids.length}个产品？`;
      
      this.$confirm(message, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log('确认删除，发送请求，ids:', ids);
        return delProduce(ids);
      }).then(() => {
        this.$message.success('删除成功');
        this.getList();
      }).catch(error => {
        console.error('删除失败:', error);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log('导出产品数据');
      this.$message.info('导出功能（静态模式）');
    },
    /** 上架/下架操作 */
    /** 单个上下架操作 */
    handleStatusChange(row, status) {
      const text = status === 1 ? '上架' : '下架';
      this.$confirm('是否确认' + text + '该产品？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateProduceStatus([row.id], status);
      }).then(() => {
        this.$message.success(text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 单个推荐/取消推荐操作 */
    handleRecommend(row) {
      const isRecommend = row.isRecommend === 1 ? 0 : 1;
      const text = isRecommend === 1 ? '推荐' : '取消推荐';
      
      this.$confirm('是否确认' + text + '该产品？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateProduceRecommend([row.id], isRecommend);
      }).then(() => {
        this.$message.success(text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 批量上架/下架 */
    /** 批量上下架操作 */
    handleBatchStatus(status) {
      const text = status === 1 ? '上架' : '下架';
      
      // 检查是否选中了要操作的数据
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要' + text + '的产品');
        return;
      }
      
      this.$confirm('是否确认批量' + text + '选中的产品？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateProduceStatus(this.ids, status);
      }).then(() => {
        this.$message.success('批量' + text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 批量推荐/取消推荐操作 */
    handleBatchRecommend(isRecommend) {
      const text = isRecommend === 1 ? '推荐' : '取消推荐';
      
      // 检查是否选中了要操作的数据
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要' + text + '的产品');
        return;
      }
      
      this.$confirm('是否确认批量' + text + '选中的产品？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateProduceRecommend(this.ids, isRecommend);
      }).then(() => {
        this.$message.success('批量' + text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 导出产品数据 */
    handleExport() {
      this.loading = true;
      exportProduce().then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        link.download = '产品数据_' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}') + '.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.product-container {
  /* 搜索表单样式 */
  .search-form {
    background: #fff;
    padding: 18px 16px 6px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    ::v-deep .el-form-item {
      margin-bottom: 12px;
    }
    
    ::v-deep .el-input__inner,
    ::v-deep .el-input__inner:focus {
      transition: all 0.3s ease;
    }
    
    ::v-deep .el-input__inner:hover {
      border-color: #c0c4cc;
    }
    
    ::v-deep .el-input__inner:focus {
      border-color: #409EFF;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }

  /* 表格容器样式 */
  .product-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;

    /* 产品名称样式 */
    .product-name {
      color: #303133;
      font-weight: 600;
      font-size: 14px;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #409EFF;
      }
    }

    /* 商户名称样式 */
    .merchant-name {
      color: #606266;
      font-size: 13px;

      i {
        color: #409EFF;
        margin-right: 6px;
        font-size: 16px;
      }
    }

    /* 价格样式 */
    .price-text {
      color: #E6A23C;
      font-weight: bold;
      font-size: 14px;
    }

    /* 时间样式 */
    .time-wrapper {
      color: #909399;
      font-size: 13px;

      i {
        margin-right: 4px;
        color: #C0C4CC;
      }
    }

    /* 表格行悬停效果 */
    ::v-deep .el-table__row {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }
    }
  }

  /* 按钮行样式 */
  .mb8 {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    ::v-deep .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }

  /* 分页样式 */
  ::v-deep .pagination-container {
    margin-top: 16px;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    /* 分页按钮动画 */
    .el-pager li {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      }
      
      &.active {
        animation: pulse 0.5s ease;
      }
    }
    
    @keyframes pulse {
      0% {
        transform: scale(1);
      }
      50% {
        transform: scale(1.1);
      }
      100% {
        transform: scale(1);
      }
    }
    
    /* 上一页/下一页按钮动画 */
    .btn-prev, .btn-next {
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
        color: #409EFF;
      }
    }
  }
}


</style>

